package com.spasvo.dirsyn.listener;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.ftp.AbstractFtp;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ssh.Sftp;
import com.spasvo.dirsyn.cfg.FTPConfig;
import com.spasvo.dirsyn.cfg.FolderConfig;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationObserver;

import java.io.File;
import java.util.List;

@Slf4j
@Data
public class SynFileListener implements FileAlterationListener {




    private FolderConfig folderConfig;

    private AbstractFtp ftp;
    private String localPath;
    private String ftpPath;
    //时间范围内多次触发执行最后一次
    private long time = 500;



    public SynFileListener(FolderConfig folderConfig) {
        this.folderConfig = folderConfig;
        FTPConfig ftpConfig = folderConfig.getFtpConfig();
        try {
            if (ftpConfig.isFtp()) {
                ftp = new Ftp(ftpConfig.getIp(), ftpConfig.getPort(), ftpConfig.getName(), ftpConfig.getPassword());
            } else {
                ftp = new Sftp(ftpConfig.getIp(), ftpConfig.getPort(), ftpConfig.getName(), ftpConfig.getPassword());
            }
            ftp.cd(folderConfig.getFtpPath());
            log.info("FolderID {} Start Listener", folderConfig.getId());

            localPath = folderConfig.getLocalPath().replaceAll("\\\\", "/");
            if (!localPath.endsWith("/"))
                localPath += "/";

            ftpPath = folderConfig.getFtpPath().replaceAll("\\\\", "/");
            if (!ftpPath.endsWith("/"))
                ftpPath += "/";

            if(folderConfig.isStartSyn()){
                log.info("FolderID {} Start Syn.",folderConfig.getId());
                ftp.delDir(ftpPath);
                ftp.mkdir(ftpPath);
                FileUtil.loopFiles(localPath).forEach(file->{
                    if(file.exists()){
                        if(file.isDirectory()){
                            onDirectoryCreate(file);
                        }else if(file.isFile()){
                            onFileCreate(file);
                        }
                    }
                });
            }

        } catch (RuntimeException e) {
            log.error("FolderID {} {} Connect Error.", folderConfig.getId(), ftpConfig.isFtp() ? "FTP" : "SFTP", e);
        }


    }

    @Override
    public void onStart(FileAlterationObserver fileAlterationObserver) {

    }

    @Override
    public void onDirectoryCreate(File file) {
        if (ftp == null) return;
        log.info("Folder Create Start Syn. FolderName {}", file.getName());
        String folderName = file.getAbsolutePath().replaceAll("\\\\", "/");
        ftp.mkDirs(ftpPath + folderName.replaceAll(localPath, ""));
        log.info("FolderName {} Syn Success.", file.getName());
    }

    @Override
    public void onDirectoryChange(File file) {
    }

    @Override
    public void onDirectoryDelete(File file) {
        if (ftp == null) return;
        log.info("Folder Delete Start Syn. FolderName {}", file.getName());
        String folderName = file.getAbsolutePath().replaceAll("\\\\", "/");
        ftp.delDir(ftpPath + folderName.replaceAll(localPath, ""));
        log.info("FolderName {} Syn Success.", file.getName());
    }

    @Override
    public void onFileCreate(File file) {
        if (ftp == null) return;
        // /root/testDir1/a.txt<==目录 File Create Start Syn. FileName a.txt
        // /root/testDir1/bb/bbb/bbb.txt<==目录 File Create Start Syn. FileName bbb.txt
        log.info(file.getAbsolutePath() + "<==目录 File Create Start Syn. FileName {}", file.getName());
        String folderName = file.getAbsolutePath().replaceAll("\\\\", "/").replaceAll(localPath, "");
        ///root/testDir1/<==localPath. FileName a.txt
        // /root/testDir1/<==localPath. FileName bb/bbb/bbb.txt
        log.info(localPath + "<==localPath. FileName {}", folderName);
        try {
            //a.txt上传文件到ftp服务器a.txt
            // bbb.txt上传文件到ftp服务器bb/bbb/bbb.txt
            String dir = folderName.substring(0,folderName.length()-file.getName().length());
            log.info(file.getName() + "上传文件到ftp服务器" + (ftpPath+dir));
            log.info("123456");
            List<String> list = ftp.ls(ftpPath);
            for(String s:list)
            {
                log.info(s + ",");
            }


//            log.info("" +ftp.exist(ftpPath+dir));
//            if(dir.length() > 0 && !ftp.exist(ftpPath+dir))
            if(dir.length() > 0)
            {
                ftp.mkDirs(ftpPath+dir);
                log.info("上传文件到ftp服务器--创建目录" + ftpPath+dir);
            }
            log.info(ftpPath+" :ftpPath--上传目录" + ftpPath + folderName.replaceAll(file.getName(), ""));
            ftp.upload(ftpPath + folderName.replaceAll(file.getName(), ""), file);
            log.info("FileName {} Syn Success.", file.getName());
        }
        catch (Exception e)
        {
            log.error("",e);
        }
    }

    @Override
    public void onFileChange(File file) {
        if (ftp == null) return;
        log.info("File Change Start Syn. FileName {}", file.getName());
        String folderName = file.getAbsolutePath().replaceAll("\\\\", "/").replaceAll(localPath, "");
        ftp.upload(ftpPath + "/" + folderName.replaceAll(file.getName(), ""), file);
        log.info("FileName {} Syn Success.", file.getName());
    }

    @Override
    public void onFileDelete(File file) {
        if (ftp == null) return;
        log.info("File Delete Start Syn. FileName {}", file.getName());
        String folderName = file.getAbsolutePath().replaceAll("\\\\", "/").replaceAll(localPath, "");
        if (ftp.exist(ftpPath + "/" + folderName)) {
            ftp.delFile(ftpPath + "/" + folderName);
            log.info("FileName {} Syn Success.", file.getName());
        } else {
            log.warn("Server Not Fount FileName {}", file.getName());
        }
    }

    @Override
    public void onStop(FileAlterationObserver fileAlterationObserver) {

    }
}
